package com.tangpian.framework.security;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;

import com.tangpian.framework.entity.User;
import com.tangpian.framework.service.user.AccountService;

public class ShiroDbRealm extends AuthorizingRealm {

	private AccountService accountService;

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String userId = (String) principals.getPrimaryPrincipal();
		User user = accountService.getUser(userId);
		Set<String> roles = user.getRoles();
		return new SimpleAuthorizationInfo(roles);
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {

		UsernamePasswordToken token2 = (UsernamePasswordToken) token;
		User user = accountService.findUserByUsername(token2.getUsername());
		String principal = user.getId();
		String credentials = user.getPassword();

		return new SimpleAuthenticationInfo(principal, credentials,
				new SimpleByteSource(accountService.getSalt()), getName());
	}
}
